﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Configuration;

public class Utils
{
    public enum Constants
    {
        Undefined = 0,
        SystemRoleType = 1,
        PasswordStatus = 2,
        ZiSaptamina = 3,
        CountryList = 4,
        LocationByCountry = 5,
        SexList = 6,
        GradDeRudenie = 7,
        LanguageList = 8
    }

	public Utils()
	{		
	}

    public static string ReplaceAcronim(string sourceText)
    {
        //N instead Ñ
        string result = sourceText;

        result = result.Replace('Ñ', 'N');
        result = result.Replace('Ñ', 'N');
        result = result.Replace('í', 'i');
        result = result.Replace('í', 'i');
        result = result.Replace('ª', 'a');
        result = result.Replace('º', ' ');
        result = result.Replace('?', ' ');

        result = result.Replace('Á', 'A');
        result = result.Replace('Â', 'A');
        result = result.Replace('Ã', 'A');
        result = result.Replace('À', 'A');
        result = result.Replace('Ç', 'C');
        result = result.Replace('É', 'E');
        result = result.Replace('È', 'E');
        result = result.Replace('Ê', 'E');
        result = result.Replace('Í', 'I');
        result = result.Replace('Ï', 'I');
        result = result.Replace('Ó', 'O');
        result = result.Replace('Ö', 'O');
        result = result.Replace('Ô', 'O');
        result = result.Replace('Õ', 'O');
        result = result.Replace('Ú', 'U');
        result = result.Replace('Ü', 'U');
        result = result.Replace('ô', 'o');
        result = result.Replace('ö', 'o');
        result = result.Replace('ó', 'o');
        result = result.Replace('õ', 'o');
        result = result.Replace('í', 'i');
        result = result.Replace('ê', 'e');
        result = result.Replace('é', 'e');
        result = result.Replace('è', 'e');
        result = result.Replace('ç', 'c');
        result = result.Replace('à', 'a');
        result = result.Replace('â', 'a');
        result = result.Replace('á', 'a');
        result = result.Replace('ã', 'a');
        result = result.Replace('ü', 'u');
        result = result.Replace('ú', 'u');
        result = result.Replace('ï', 'i');
        result = result.Replace('ø', 'o');

        return result;
    }

    public string ConvertDataTableToString(DataTable sourceDataTable, string columnName)
    {
        string resultString = string.Empty;

        if (sourceDataTable != null && sourceDataTable.Rows.Count > 0)
        {
            for (int i = 0; i < sourceDataTable.Rows.Count; i++)
            {
                if (i > 0)
                {
                    resultString += ", ";
                }
                resultString += "'" + sourceDataTable.Rows[i][columnName].ToString() + "'";
            }
        }
        else
        {
            resultString = string.Empty;
        }

        return resultString;
    }

    public List<string> ConvertDataTableToList(DataTable mSelected, string columnName)
    {
        List<string> resultList = new List<string>();

        if (mSelected != null && mSelected.Rows.Count > 0)
        {
            for (int i = 0; i < mSelected.Rows.Count; i++)
            {
                resultList.Add(mSelected.Rows[i][columnName].ToString());
            }
        }

        return resultList;
    }

    public string ConvertListToString(List<string> mSelected)
    {
        string resultString = string.Empty;

        if (mSelected != null && mSelected.Count > 0)
        {
            for (int i = 0; i < mSelected.Count; i++)
            {
                if (i > 0)
                {
                    resultString += ",";
                }
                resultString += "'" + mSelected[i] + "'";
            }
        }
        else
        {
            resultString = string.Empty;
        }

        return resultString;
    }

    public static string UserDataValue(DataTable userData, string fieldName)
    {
        string toReturn = string.Empty;

        try
        {
            if (userData != null && userData.Rows.Count > 0)
            {
                toReturn = userData.Rows[0][fieldName] != DBNull.Value ? userData.Rows[0][fieldName].ToString() : string.Empty;
            }
        }
        catch 
        {
            toReturn = string.Empty;
        }

        return toReturn;
    }

    // Hash an input string and return the hash as
    // a 32 character hexadecimal string.
    public static string GetMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

    // Verify a hash against a string.
    public static bool VerifyMd5Hash(string input, string hash)
    {
        // Hash the input.
        string hashOfInput = GetMd5Hash(input);

        // Create a StringComparer an compare the hashes.
        StringComparer comparer = StringComparer.OrdinalIgnoreCase;

        if (0 == comparer.Compare(hashOfInput, hash))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
     
    #region Email Settings

    public static string EmailTemplate(string toEmail, string[] replaceFields, string[] fieldsArray, string legalEntity, DataTable templateTable, int languageID, int event_type)
    {
        string response = string.Empty;
        try
        {
            if (templateTable != null && templateTable.Rows.Count == 1)
            {
                string emailSubject = templateTable.Rows[0]["subject"].ToString();
                string emailTemplate = templateTable.Rows[0]["text"].ToString();
                if (emailTemplate != null && emailTemplate.Length > 0)
                {
                    if (fieldsArray != null && fieldsArray.Length > 0)
                    {
                        for (int indexKey = 0; indexKey < fieldsArray.Length; indexKey++)
                        {
                            emailTemplate = emailTemplate.Replace("[" + fieldsArray[indexKey].Trim() + "]", replaceFields[indexKey]);
                        }
                    }
                }

                response = EmailSend(toEmail, emailTemplate, emailSubject);
            }
        }
        catch (Exception e)
        {
            response = "Error sending mail: Exception!!!" + e.Message;
        }
        return response;
    }

    public static string EmailSend(string toEmail, string emailTemplate, string emailSubject)
    {
        string response = string.Empty;

        try
        {
            string to = toEmail;
            string smtpHost = ConfigurationManager.AppSettings["smtpHost"];

            string emailFrom = ConfigurationManager.AppSettings["emailFrom"];

            if (!string.IsNullOrEmpty(emailFrom.Trim()))
            {

                string fromDisplay = ConfigurationManager.AppSettings["fromDisplay"];
                string smtpUser = ConfigurationManager.AppSettings["smtpUser"];
                string password = ConfigurationManager.AppSettings["smtpPassword"];

                int smtpPort = 25;
                int.TryParse(ConfigurationManager.AppSettings["smtpPort"], out smtpPort);
                if (smtpPort == 0)
                {
                    smtpPort = 25;
                }

                string body = @"<html><body><div style=""font-family:arial;font-size:12pt;"">";

                if (emailTemplate.Trim() != string.Empty)
                {
                    body += "<pre>";
                    body += emailTemplate;
                    body += "</pre>";
                    body += @"</div></body></html>";

                    // AuthTypes: "Basic", "NTLM", "Digest", "Kerberos", "Negotiate"
                    string authType = "Basic";
                    string bccTo = string.Empty;
                    string copyTo = string.Empty;

                    response = SendEmail(emailFrom, fromDisplay, to, emailFrom, emailFrom, copyTo, bccTo, emailSubject,
                        body, System.Text.Encoding.ASCII, System.Text.Encoding.UTF8,
                        true, smtpHost, smtpUser, password, smtpPort, authType);
                }
                else
                {
                    response = "Unable to send to an empty email address!";
                }
            }
            else
            {
                response = "Error. Empty address in from field.";
            }
        }
        catch (Exception e)
        {
            response = "Error sending mail: Exception!!!" + e.Message;
        }

        return response;
    }

    static string SendEmail(string from, string fromDisplay, string to, string sender,
       string replyTo, string copyTo, string bccTo, string subject, string body, System.Text.Encoding subjectEncoding,
       System.Text.Encoding bodyEncoding, bool isBodyHtml, string smtpHost, string smtpUser,
       string smtpPass, int smtpPort, string smtpAuthType)
    {
        string response = null;
        System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(from, fromDisplay);
        System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(to);
        System.Net.Mail.MailAddress senderAddress = new System.Net.Mail.MailAddress(sender);
        System.Net.Mail.MailAddress replyToAddress = new System.Net.Mail.MailAddress(replyTo);
        System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage(fromAddress, toAddress);

        if (!copyTo.Equals(string.Empty))
        {
            System.Net.Mail.MailAddress copyToAddress = new System.Net.Mail.MailAddress(copyTo);
            emailMessage.CC.Add(copyToAddress);
        }

        if (!bccTo.Equals(string.Empty))
        {
            System.Net.Mail.MailAddress bccToAddress = new System.Net.Mail.MailAddress(bccTo);
            emailMessage.Bcc.Add(bccToAddress);
        }

        emailMessage.Body = body;
        emailMessage.Sender = senderAddress;
        emailMessage.ReplyTo = replyToAddress;
        emailMessage.SubjectEncoding = subjectEncoding;
        emailMessage.BodyEncoding = bodyEncoding;
        emailMessage.Subject = subject;
        emailMessage.IsBodyHtml = isBodyHtml;
        emailMessage.Priority = System.Net.Mail.MailPriority.High;

        System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpHost);
        bool enableSsl = true;
        bool.TryParse(ConfigurationManager.AppSettings["EnableSsl"], out enableSsl);

        smtp.EnableSsl = enableSsl;
        smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

        // Note: on GoDaddy host the creadentials are unnecessary
        bool withCredentials = false;
        bool.TryParse(ConfigurationManager.AppSettings["smtpUseCredentials"], out withCredentials);
        if (withCredentials)
        {
            smtp.UseDefaultCredentials = false;
            System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(smtpUser, smtpPass);
            smtp.Credentials = (System.Net.ICredentialsByHost)networkCredential.GetCredential(smtpHost, smtpPort, smtpAuthType);
        }

        try
        {
            smtp.Send(emailMessage);
        }
        catch (System.Net.Mail.SmtpException smtpException)
        {
            response = smtpException.Message;
            response = response.Replace("\r\n", "");
            response = response.Replace("\"", "");
            response = response.Insert(0, "SMTP Agent Error: ");
        }
        catch (Exception ex)
        {
            response = ex.Message;
            response = response.Replace("\r\n", "");
            response = response.Replace("\"", "");
            response = response.Insert(0, "Error: ");
        }
        return response;
    }



    #endregion Email Settings

}